package com.monkey.luffer.springboot.demo.basis.kcc.s3cmd;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author jiahong.liu
 * @since 2023/6/28 15:44
 */
public class CreateTicket {

    private static final String COOKIE = "G_ENABLED_IDPS=google; csrftoken=dizIYryVeX4SyoETDJCxDkfrAb7qA7iniZVnwB763TBcMNrUMWLFoMUSLrM5KxpF";

    private static final String AUTH = "pUesMgMLYFtlZsLQo5OyQ4qjg5O6yVofzPNl6gXPvMpZPfqFR1bEwLvFLukK9aDdw5GJHP7qQ7Ftum3G7KuTlFPixqrUaIQ2i0fo9miszWrv6SegvTMnzu9EoPWN3Dvj1UICwYhRbEVvplnFAgvXm9j9jB52J1zOwdbStEBKcIKEbEj6oG7GA6trspYC0cfe2USKcJvoAdJBUmcQgVjZT1NHBkw6pZuV4rhVEPsUWJ6AK8qvL9KSwZSK3hAEcXvD";
    private static final String QUERY_STRING = "mutation CreateTicketMutation(\n  $input: CreateTicketInput!\n  $first: Int\n  $filters: String\n  $sorts: String\n  $userView: Boolean!\n  $agentView: Boolean!\n) {\n  createTicket(input: $input) {\n    ticket {\n      id\n    }\n    viewer {\n      id\n      isAgent\n      ...AgentTicketsPage_viewer_1sVwDG @include(if: $agentView)\n      ...UserTicketsPage_viewer_1sVwDG @include(if: $userView)\n    }\n  }\n}\n\nfragment AgentDashboard_viewer on Viewer {\n  id\n  agentDashboardTickets(first: 10000) {\n    ...TemplatesDashboard_tickets\n    ...PieChartDashboard_tickets\n  }\n  ...StatisticDashboard_viewer\n}\n\nfragment AgentTicketsPage_viewer_1sVwDG on Viewer {\n  id\n  viewableAgentTicketsCount(filters: $filters, searchWords: \"\")\n  viewableAgentTickets(first: $first, filters: $filters, searchWords: \"\", page: 0, numRowsPerPage: 20, sorts: $sorts) {\n    ...TicketTable_tickets\n    pageInfo {\n      hasNextPage\n      hasPreviousPage\n      startCursor\n      endCursor\n    }\n  }\n  ...AgentDashboard_viewer\n}\n\nfragment PieChartDashboard_tickets on TicketConnection {\n  edges {\n    node {\n      id\n      createdAt\n    }\n  }\n}\n\nfragment StatisticDashboard_viewer on Viewer {\n  agentDashboardStatusCount\n}\n\nfragment TemplatesDashboard_tickets on TicketConnection {\n  edges {\n    node {\n      id\n      template {\n        name\n        id\n      }\n    }\n  }\n}\n\nfragment TicketRow_ticket on Ticket {\n  id\n  ticketId\n  name\n  applicantUser {\n    name\n    id\n  }\n  assigneeTeam {\n    name\n    id\n  }\n  assigneeUser {\n    name\n    id\n  }\n  status\n  createdAt\n  modifiedAt\n  template {\n    name\n    id\n  }\n  unreplyComment\n}\n\nfragment TicketTable_tickets on TicketConnection {\n  edges {\n    node {\n      id\n      ...TicketRow_ticket\n    }\n  }\n}\n\nfragment UserTicketsPage_viewer_1sVwDG on Viewer {\n  id\n  viewableUserTicketsCount(filters: $filters, searchWords: \"\")\n  viewableUserTickets(first: $first, filters: $filters, searchWords: \"\", page: 0, numRowsPerPage: 20, sorts: $sorts) {\n    edges {\n      __typename\n      cursor\n      node {\n        __typename\n        id\n      }\n    }\n    ...TicketTable_tickets\n    pageInfo {\n      hasNextPage\n      hasPreviousPage\n      startCursor\n      endCursor\n    }\n  }\n}\n";

    private static final String NON_LIVE_DDL_TEMPLATE_ID = "VGVtcGxhdGU6ODI3Mw==";

    private static final String NON_LIVE_DML_TEMPLATE_ID = "VGVtcGxhdGU6ODI3NA==";

    private static final String LIVE_DDL_TEMPLATE_ID = "VGVtcGxhdGU6ODI3OA==";

    private static final String LIVE_DML_TEMPLATE_ID = "VGVtcGxhdGU6ODI3OQ==";

    private static final String SORTS = "{\"sorts\":[\"-created_at\"]}";

    private static final String FILTERS = "{\"statuses\":[\"draft\",\"pending_approval\",\"open\",\"processing\",\"completed\"],\"types\":[],\"teams\":[],\"templates\":[],\"applicants\":[],\"assignees\":[],\"id\":\"\",\"title\":\"\"}";

    private static final String FORM_DATA = "{\"Team\":\"SG - Core Banking\",\"TargetEnv\":[\"{TargetEnv}\"],\"TableName\":\"{TableName}\",\"DBDNS\":\"{DBDNS}\",\"Remarks\":\"{Remarks}\"}";

    private static  Map<String, String> NonLiveTemplateMap;

    private static  Map<String, String> LiveTemplateMap;

    static {
        NonLiveTemplateMap = new HashMap<>();
        LiveTemplateMap = new HashMap<>();
        NonLiveTemplateMap.put("DDL", NON_LIVE_DDL_TEMPLATE_ID);
        NonLiveTemplateMap.put("DML", NON_LIVE_DML_TEMPLATE_ID);
        LiveTemplateMap.put("DDL", LIVE_DDL_TEMPLATE_ID);
        LiveTemplateMap.put("DML", LIVE_DML_TEMPLATE_ID);
    }

    public void createTicket(String env, Map<String, String> map) throws IOException {
        String formData = FORM_DATA;
        String templateId;
        if ("staging".equals(env)) {
            formData = formData.replace("{TargetEnv}", "SG Staging");
            templateId = NonLiveTemplateMap.get(map.get("sql"));

        } else {
            formData = formData.replace("{TargetEnv}", "SG Live");
            templateId = LiveTemplateMap.get(map.get("sql"));
        }
        formData = formData.replace("{DBDNS}", map.get("db-address"));
        formData = formData.replace("{TableName}", map.get("tableNames"));
        formData = formData.replace("{Remarks}", map.get("content"));
        createTicket(formData, templateId, map.get("name"));
    }


    public void createTicket(String formData, String templateId, String name) throws IOException {
        HttpPost httpPost = new HttpPost("http://www.baidu.com");
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36");
        httpPost.setHeader("Authorization", "Bearer " + AUTH);
        httpPost.setHeader("Host", "gts-sg.seabank.io");
        httpPost.setHeader("content-type", "application/json");
        BasicCookieStore cookieStore = new BasicCookieStore();
        setCookie(cookieStore);
        CloseableHttpClient httpClient = HttpClientBuilder.create()
                .setDefaultCookieStore(cookieStore)
                .build();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("query", QUERY_STRING);
        JSONObject variables = new JSONObject();
        variables.put("agentView", false);
        variables.put("userView", true);
        variables.put("sorts", SORTS);
        variables.put("first", 20);
        variables.put("filters", FILTERS);
        JSONObject input = new JSONObject();
        input.put("templateId", templateId);
        input.put("name", name);
        input.put("reviewerIds", new JSONArray());
        input.put("watcherIds", new JSONArray());
        input.put("formData", formData);
        input.put("product", "Maribank:SG Bank");
        input.put("reviewer", "VXNlcjo0MjU2");
        variables.put("input", input);
        jsonObject.put("variables", variables);
        StringEntity entity = new StringEntity(jsonObject.toJSONString(), "utf-8");
        httpPost.setEntity(entity);

        HttpResponse response = null;
        try {
            // 执行请求
            response = httpClient.execute(httpPost);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println("内容长度：" + content.length());
            }
        } catch (Exception e) {

        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
        }

    }

    private void setCookie (BasicCookieStore cookieStore) {
        String[] cookieArr = COOKIE.split(";");
        for (String item : cookieArr) {
            item = item.trim();
            String[] itemArr = item.split("=");
            if (itemArr.length < 2) {
                continue;
            }
            String key = itemArr[0];
            String value = itemArr[1];
            BasicClientCookie clientCookie = new BasicClientCookie(key, value);
            cookieStore.addCookie(clientCookie);
        }
    }
}
